import { inject, h, render } from "vue";


export default function () {
    const $message = inject("$message")
    // 渲染vnode
    function renderContent(content, dom) {
        try {
            const json = JSON.parse(content);
            validateXss(json);
            const { type, props, children } = json;
            const vnode = h(type, props, getChildrenVnode(children));
            render(vnode, dom);
        } catch (error) {
            $message({ message: error.message, type: "warning" });
        }
    };

    // 将json的children转换为vnode
    function getChildrenVnode(children) {
        if (typeof children === "string") {
            return children;
        } else if (Array.isArray(children)) {
            return children.reduce((pre, { type, props, children: _children }) => {
                pre.push(h(type, props, getChildrenVnode(_children)));
                return pre;
            }, []);
        } else {
            return "";
        }
    };

    // 校验xss攻击
    function validateXss(json) {
        const { type, props, children } = json;
        if (type === "script") {
            throw new Error("标签不合法");
        } else {
            Array.isArray(children) && validateXss(children);
        }
    }

    // 格式化json
    function formatContent(content) {
        try {
            const json = JSON.parse(content);
            validateXss(json);
            return JSON.stringify(json, null, 2);
        } catch (error) {
            $message({ message: error.message, type: "warning" });
        }
    };

    return {
        renderContent,
        getChildrenVnode,
        validateXss,
        formatContent
    }
}